#include "util.hpp"
#include <sys/types.h>
#include <functional>
#include <vector>

using namespace std;
using func_t = std::function<void()>;

#define INIT(v)                    \
    do                             \
    {                              \
        cbs.push_back(printLog);   \
        cbs.push_back(downLoad);   \
        cbs.push_back(executeSql); \
    } while (0)

#define EXEC_OTHER(v)            \
    do                           \
    {                            \
        for (auto const &cb : v) \
            cb();                \
    } while (0)

void test1()
{
    vector<func_t> cbs;

    INIT();

    setNonBlock(0);
    char buffer[1024];
    while (true)
    {
        std::cout << ">>> ";
        fflush(stdout);
        ssize_t s = read(0, buffer, sizeof(buffer));
        if (s > 0)
        {
            buffer[s - 1] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (s == 0)
        {
            std::cout << "read end" << std::endl;
        }
        else
        {
            // 1. 当没有输入, 又非阻塞, return -1
            // 2. 要结合返回值和错误值一起看
            if(errno == EAGAIN)
            {
                cout << "resource is unavaliable" << endl;
                EXEC_OTHER(cbs);
            }
            else if(errno == EINTR)
            {
                continue;
            }
            else
            {
                cout << "s : " << s << " errno : " << strerror(errno) << endl;
                return;
            }
        }

        sleep(1);
    }
}

int main()
{
    test1();
    return 0;
}